package com.example.mqttledmenu;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.UUID;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class DetailsActivity extends AppCompatActivity {
    private static final String[] PERMISSIONS_STORAGE = new String[0];
    private static final String REQUEST_EXTERNAL_STORAGE = "请求权限";
    private Button download_btn;
    private String detail_file_download = "";
    private TextView file_name;
    LinearLayout detail_file_visible;

    public void setNewsRead(String news_id) {
        //标记新闻已读
        Retrofit retrofit = new Retrofit.Builder().baseUrl(Config.serverUrl).build();
        UploadService uploadService = retrofit.create(UploadService.class);
        Call<ResponseBody> call = uploadService.hasRead(Config.getInstance().getUserId(), news_id);
        call.enqueue(new Callback<ResponseBody>() {
            @SuppressLint("CheckResult")
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.body() != null) {
                    try {
                        String result = response.body().string();
                        JsonObject returnData = new JsonParser().parse(result).getAsJsonObject();
                        if (!returnData.get("code").toString().equals("200")) {
                            Toast.makeText(DetailsActivity.this, "服务端错误~", Toast.LENGTH_SHORT).show();
                        } else {
                            //对数据进行处理
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    Log.d("nightowl", "onResponse -- > " + "返回数据为空");
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.d("nightowl", "onFailure -- > " + t.toString());
            }
        });

    }

    public void loadNewsInfo(String news_id) {
        //获取新闻的详细数据
        Retrofit retrofit = new Retrofit.Builder().baseUrl(Config.serverUrl).build();
        UploadService uploadService = retrofit.create(UploadService.class);
        Call<ResponseBody> call = uploadService.getDetail(news_id);
        call.enqueue(new Callback<ResponseBody>() {
            @SuppressLint("CheckResult")
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.body() != null) {
                    try {
                        String result = response.body().string();
                        JsonObject returnData = new JsonParser().parse(result).getAsJsonObject();
                        if (!returnData.get("code").toString().equals("200")) {
                            Toast.makeText(DetailsActivity.this, "服务端错误~", Toast.LENGTH_SHORT).show();
                        } else {
                            //对数据进行处理
                            JsonObject temp = new JsonParser().parse(returnData.get("data").toString()).getAsJsonObject();
                            Log.d("nightowl", "新闻详情信息：（锚点二） " + temp);
                            ImageView detail_avatar = findViewById(R.id.detail_avatar);
                            TextView detail_title = findViewById(R.id.detail_title);
                            TextView detail_publisher = findViewById(R.id.detail_publisher);
                            TextView detail_apartment = findViewById(R.id.detail_apartment);
                            TextView detail_contents = findViewById(R.id.detail_contents);
                            TextView detail_time = findViewById(R.id.detail_time);
                            RequestOptions requestOptions = new RequestOptions()
                                    .placeholder(R.drawable.loading)
                                    .error(R.drawable.unknow_person)
                                    .fallback(R.drawable.unknow_person);
                            requestOptions.centerCrop().transform(new CircleCrop());
                            Glide.with(DetailsActivity.this)
                                    .load(temp.get("authorAvatar").toString().replace("\"", "").replace("\\", ""))
                                    .apply(requestOptions)
                                    .into(detail_avatar);
                            detail_title.setText(temp.get("newsTitle").toString().replace("\"", ""));
                            detail_publisher.setText(temp.get("newsAuthor").toString().replace("\"", ""));
                            detail_apartment.setText(temp.get("newsDepartment").toString().replace("\"", ""));
                            detail_contents.setText("    " + temp.get("newsContent").toString().replace("\"", ""));
                            detail_time.setText(temp.get("newsPublishTime").toString().replace("\"", ""));


                            //处理下载按钮的可见性
                            if (temp.get("newsAppendix").toString().equals("null")) {
                                detail_file_visible.setVisibility(View.INVISIBLE);
                            } else {
                                detail_file_download = temp.get("newsAppendix").toString().replace("\"", "");
                                file_name = findViewById(R.id.file_name);
                                file_name.setText(detail_file_download.substring(detail_file_download.lastIndexOf("/") + 1));
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    Log.d("nightowl", "onResponse -- > " + "返回数据为空");
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.d("nightowl", "onFailure -- > " + t.toString());
            }
        });
    }

    public void downloadFile(String targetUrl) {
        String suffixName = targetUrl.substring(targetUrl.lastIndexOf("."));
        String dirName = "campus_notice/";
        String fileName = UUID.randomUUID().toString().replace("-", "") + suffixName;
        Download download = new Download(this, targetUrl, dirName, fileName);
        Toast.makeText(DetailsActivity.this, "已存储到相册！", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_details);
        String news_id = getIntent().getExtras().getString("news_id");
        Log.d("nightowl", "新闻详情信息：（锚点二） " + news_id);
        boolean need_read = getIntent().getExtras().getBoolean("need_read");
        if (need_read) {
            setNewsRead(news_id);
        }
        //获取对应的页面锚点
        download_btn = findViewById(R.id.detail_file_download);
        detail_file_visible = findViewById(R.id.detail_file_visible);
        loadNewsInfo(news_id);
        download_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                downloadFile(detail_file_download);
            }
        });
    }
}